package com.custom.base.http


import android.util.Log
import android.view.Gravity
import android.widget.Toast
import com.google.gson.Gson
import com.custom.base.config.BaseConfig
import com.custom.base.manager.SDActivityManager
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type


/**
 * 作者：
 * 日期：2019/8/15
 * 描述：
 */
abstract class SDOkHttpResoutCallBack<E>(
    var isFailToast:Boolean? = null, //是否在失败的时候提示toast
    var gravity:Int = Gravity.BOTTOM //显示位置
) : OkHttpCallback.Callback() {
    private var actModel: E? = null

    override fun onSuccessBase(result: String) {
        val type: Type? = (javaClass.genericSuperclass as ParameterizedType?)?.actualTypeArguments?.get(0)
        actModel = try {
            Gson().fromJson(result, type)
        }catch (e: Exception) {
            e.printStackTrace()
            Gson().fromJson("{\"${BaseConfig.getInstance.getSuccessCodeName()}\": 0,\"${BaseConfig.getInstance.getSuccessMsgName()}\": \"" + e.message + "\"}", type)
        }
        super.onSuccessBase(result)
    }

    abstract fun onSuccess(entity: E)
    fun onFailures(code: Int, msg: String) {}
    override fun onSuccess(result: String) {
        if(actModel == null){
            onFailures(-1, "")
        }else{
            onSuccess(actModel!!)
        }

    }

    override fun onFailure(code: Int, msg: String) {
        onFailures(code, msg)
        val isToast = if(isFailToast == null) BaseConfig.getInstance.isHttpFailToast() else isFailToast!!
        Log.e("~~~", "onFailure:$code $msg" )
        if (!SDActivityManager.instance.isEmpty) {
            if (isToast && msg != "" && msg != "null" && code != -1)
                if (!SDActivityManager.instance.isEmpty) {
                    Toast.makeText(SDActivityManager.instance.lastActivity, msg, Toast.LENGTH_SHORT)
                        .show()
                }
        }
    }
}
